package org.jground.rx.ui.zk.viewControl;

import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.codetable.Codetable;
import org.jground.codetable.CodetableElement;
import org.jground.codetable.DefaultCodetable;
import org.jground.codetable.DefaultCodetableElement;
import org.jground.rx.RXAttribute;
import org.jground.rx.RXSystem;
import org.jground.rx.RXTypeCodetable;
import org.jground.rx.RXView;
import org.jground.rx.ui.zk.UIFrame;
import org.jground.util.ArrayUtils;
import org.jground.util.L;
import org.zkoss.zul.Label;

public class UIAttributeViewCodetable extends UIAttributeViewBase {

    private static Log logger = LogFactory.getLog(UIAttributeViewCodetable.class);

    public UIAttributeViewCodetable createNew(UIFrame uiFrame, RXView moView) {
        return new UIAttributeViewCodetable(uiFrame, moView);
    }

    public UIAttributeViewCodetable() {}

    private String[] codes;
    private Label valueLabel;
    private String codeTableName;

    private UIAttributeViewCodetable(UIFrame uiFrame, RXView moView) {
        super(uiFrame, moView);
        RXAttribute moAttribute = moView.getRXAttribute();
        RXTypeCodetable ctype = (RXTypeCodetable) moAttribute.getRXType().getBaseType();
        codeTableName = ctype.getCodeTableName();
        L.debug(logger, "codetable name", codeTableName);

        add(valueLabel = new Label());
    }

    protected Codetable getCodetable() {
        Codetable ct = null;
        try {
            ct = RXSystem.getInstance().getCtService().getCodetable(codeTableName, true);
        } catch (Exception e) {
            ct = new DefaultCodetable(codeTableName, e.toString(), new DefaultCodetableElement("--", e.toString()));
        }
        return ct;
    }

    public void set(String... codes) {
        this.codes = codes;
        clear();
        if (ArrayUtils.isNotEmpty(codes)) {
            Codetable ct = getCodetable();
            CodetableElement cte = ct.getElement(codes[0]);
            valueLabel.setValue(cte != null ? cte.getName() : "");
        }
    }

    public void clear() {
        valueLabel.setValue("");
    }

    public Collection<String> renderToString() {
        super.renderToStringS.clear();
        if (ArrayUtils.isNotEmpty(codes)) {
            for (String code : codes) {
                Codetable ct = getCodetable();
                CodetableElement cte = ct.getElement(code);
                if (cte != null) {
                    renderToStringS.add(cte.getName());
                }
            }
        }
        return renderToStringS;
    }
}
